#!/usr/bin/env python

import sys
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch

def grid(canvas, lowerLeft, numCells, cellSize):
    print lowerLeft, numCells, cellSize
    xposes = []
    yposes = []
    leftPos = lowerLeft[0]
    for cell in range(numCells[0] + 1):
        xposes.append(lowerLeft[0] + cell * cellSize[0])

    for cell in range(numCells[1] + 1):
        yposes.append(lowerLeft[1] + cell * cellSize[1])

    canvas.grid(xposes, yposes)


def main(args=None):
    if args == None:
        args = sys.argv[1:]

    pageSize = (8.5 * inch, 11 * inch)
    squareSize = (0.25 * inch, 0.25 * inch)
    boardSizeInSquares = (9, 9)
    boxSizeInSquares = (3, 3)

    boardSize = (boardSizeInSquares[0] * squareSize[0],
                 boardSizeInSquares[1] * squareSize[1])

    numBoards = (int(pageSize[0]/boardSize[0]), int(pageSize[1]/boardSize[1]))
    print numBoards
    extraSpace = (pageSize[0] - numBoards[0] * boardSize[0],
                  pageSize[1] - numBoards[1] * boardSize[1])
    print (extraSpace[0]/inch, extraSpace[1]/inch)
    intraBoardSpace = (extraSpace[0]/(numBoards[0]+1), extraSpace[1]/(numBoards[1]+1))
    print intraBoardSpace

    c = canvas.Canvas("boards.pdf", pageSize)

    c.setLineCap(1) # rounded

    for i in range(numBoards[0]):
        for j in range(numBoards[1]):
            lowerLeft = (intraBoardSpace[0] + i * (intraBoardSpace[0] +  boardSize[0]),
                         intraBoardSpace[1] + j * (intraBoardSpace[1] + boardSize[1]))
            
            c.setLineWidth(1)
            grid(c, lowerLeft, boardSizeInSquares, squareSize)

            c.setLineWidth(2)
            grid(c, lowerLeft,
                 (boardSizeInSquares[0]/boxSizeInSquares[0],
                  boardSizeInSquares[1]/boxSizeInSquares[1]),
                 (boxSizeInSquares[0] * squareSize[0],
                  boxSizeInSquares[1] * squareSize[1]))

    c.showPage()
    c.save()
           
                  

    return 0


if __name__ == '__main__':
    sys.exit(main())

